package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.config.LimitRequest;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author wuyiqiang
 * @2022/6/17 16:57
 */
@RestController
@RequestMapping(value = "/user", produces = "application/json;charset=utf-8")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信    如何验证验证码？
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMas(@RequestBody User user) {
        //生成一个四位数的随机数
        // Integer code = ValidateCodeUtils.generateValidateCode4String(4);
        // String code1 =code+"";
        // 测试其他功能可使用
        String code = "1480";
        //发送短信
        // SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", user.getPhone(), code1);

        //传phone和code到redis
        redisTemplate.opsForValue().set(user.getPhone(), code, 10000L, TimeUnit.DAYS);

        return R.success("发送成功");

    }

    /**
     * 登录
     *
     * @return
     */
    @LimitRequest(count=3)
    @PostMapping("/login")
    public R login(@RequestBody User user) {

        //获取存在redis中的code
        String codeHead = redisTemplate.opsForValue().get(user.getPhone()) + "";
        //验证code是否正确
        if (!user.getCode().equals(codeHead)) {
            return R.error("验证码错误，请重新输入");
        }

        User login = userService.login(user);
        //生成token
        String token = JwtUtil.getJwtToken(user.getId(), user.getName());
        login.setToken(token);
        //传token进redis
        redisTemplate.opsForValue().set(token, user.getPhone(), 10, TimeUnit.DAYS);

        return R.success(login);

    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("/loginout")
    public R loginout(HttpServletRequest request) {
        String token = request.getHeader("AuthorizationUser");
        if (token != null) {
            redisTemplate.delete(token);
            return R.success("退出成功");
        }
        return R.error("退出失败");
    }


    /**
     * 利用token获得当前页面用户名
     *
     * @param request
     * @return
     */
    public String tokenToUsername(HttpServletRequest request) {
        //用户id设置
        String token = request.getHeader("AuthorizationUser");

        String username = (String) redisTemplate.opsForValue().get(token);


        return username;
    }

}
